package com.common.realm;

import com.common.token.JwtToken;
import com.common.util.JwtUtil;
import com.common.util.manager.AsyncManager;
import com.common.util.manager.factory.AsyncFactory;
import com.system.constant.Constants;
import com.system.entity.Teacher;
import com.system.service.PermissionService;
import com.system.service.RoleService;
import com.system.service.TeacherService;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author zfc
 * @date 2023-04-20 16:12:52
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private RoleService roleService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private PermissionService permissionService;

    @Override
    //获得自己定义的token
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.iterator().next();
        Set<String> roleNames = roleService.selectAllRoleNamesByUsername(username);

        Set<String> permission = permissionService.selectAllPermissionKeyByRoleName(roleNames);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(permission);
        return info;
    }


    //使用自定义token
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) authenticationToken;
        String token = (String) jwtToken.getPrincipal();
        Claims claims = JwtUtil.parseJWT(token);
        String username = claims.getId();
        Teacher user = teacherService.getTeacherByUserName(username);
        if (user == null){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名错误！"));
            throw new UnknownAccountException("用户名错误！！！");
        }else if (user.getIsDelete()==1){
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "账号已被注销！"));
            throw new UnknownAccountException("该账号已被注销，请联系管理员后重试！！！");
        }
        return new SimpleAuthenticationInfo(username, user.getPassword(), getName());
    }
}
